import json
from flask import Blueprint, render_template, request, current_app
import requests
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.models import Role

admin_sign_equip = Blueprint('adminSignequip', __name__, url_prefix='/admin/sign_equip')

# 获取体征设备管理页面
@admin_sign_equip.get('/')
def main():
    return render_template('admin/sign_equip/main.html')

# 体征设备分页查询
@admin_sign_equip.get('/data')
def data():
    page = request.args['page']
    page_size = request.args['limit']
    content = ''
    try:
        content = request.args['content']
    except:
        print('暂无设备名称')
    response = requests.post(url=current_app.config['EMERGENCY_URL'] + '/signs',
                             headers={
                                 'Content-type': 'application/json'
                             },
                             data=json.dumps({
                                 "page": int(page) - 1,
                                 "page_size": page_size,
                                 "total_count": True,
                                 "search": content
                             }))
    data = json.loads(response.text)
    data['code'] = 0
    data['count'] = response.headers['Total-Count']
    data['limit'] = page_size
    return data


# 情景增加
@admin_sign_equip.get('/add')
#@authorize("admin:sign_equip:add", log=True)
def add():
    roles = Role.query.all()
    return render_template('admin/sign_equip/add.html', roles=roles)


@admin_sign_equip.post('/save')
def save():

    req_json = request.json
    a = req_json.get("roleIds")
    code = xss_escape(req_json.get('code'))
    sn = xss_escape(req_json.get('sn'))
    name = xss_escape(req_json.get('name'))
    remark = xss_escape(req_json.get('remark'))
    dept_id = xss_escape(req_json.get('deptId'))

    if not code or not sn or not dept_id:
        return fail_api(msg="设备编号、sn码、部门编号不得为空")
    response = add_api(code,sn,name,remark,dept_id)
    if response['code']==200:
        return success_api(msg="增加成功")
    else :
        return fail_api(msg=response['message'])
def add_api(code,sn,name,remark,dept_id):
    body = {
        "code": code,
        "sn": sn,
        "name": name,
        "remark": remark,
        "dept_id": int(dept_id)
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/signs/create', json=body).json()
    return req

# 删除情景
@admin_sign_equip.delete('/remove/<int:id>')
@authorize("admin:sign_equip:remove", log=True)
def delete(id):
    body = {
        "ids": [id]
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/signs/delete', json=body).json()
    if req['code']==200:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg=req['message'])

#  编辑情景
@admin_sign_equip.get('/edit')
@authorize("admin:sign_equip:edit", log=True)
def edit():
    sign_equip=request.args.to_dict()
    roles = Role.query.all()
    checked_roles = []
    for r in roles:
        checked_roles.append(r.id)
    return render_template('admin/sign_equip/edit.html', sign_equip=sign_equip, roles=roles, checked_roles=checked_roles)


#  编辑情景
@admin_sign_equip.put('/update')
# @authorize("admin:sign_equip:edit", log=True)
def update():
    req_json = request.json
    req_json['dept_id'] = int(req_json['deptId'])
    print(req_json)
    req = requests.post(url=current_app.config['EMERGENCY_URL']+'/signs/update', json=req_json).json()
    if req['code'] == 200:
        return success_api(msg="更新成功")
    else:
        return fail_api(msg=req['message'])

# 批量删除
@admin_sign_equip.delete('/batchRemove')
@authorize("admin:sign_equip:remove", log=True)
def batch_remove():
    ids = list(map(int, request.form.getlist('ids[]')))
    body = {
        "ids": ids
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/signs/delete', json=body).json()
    print(req)
    if req['code']==200:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg=req['message'])